<?php defined('SYSPATH') OR die('No direct access allowed.');

class Render_Excel extends Render {

	public static function render($response, array $vars=array(), array $globals=array(), $file=FALSE, array $options=array())
	{
		if ( empty($vars['_no_header']) && ($response instanceof Response)) {
			$response->headers('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset='.Kohana::$charset);
		}

		$data = isset($vars['_data']) ? $vars['_data'] : null;
		$excel = new PHPExcel();
		$excel->setActiveSheetIndex(0);
		$sheet = $excel->getActiveSheet();
		$sheet->fromArray($data);

		$filepath = tempnam(Kohana::$cache_dir.DIRECTORY_SEPARATOR.'util', 'phpexcel_');
		$result = NULL;
		$objWriter = new PHPExcel_Writer_Excel2007($excel);
		$objWriter->save($filepath);
		if (!empty($file))
		{
			$response->x_send_file($filepath, $file);
		}
		else
		{
			$result = file_get_contents($filepath);
			@unlink($filepath);
			
		}
		return $result;
	}

}